package jcommon.chap2_string;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.math.stat.StatUtils;

public class FindingNested {
	public static void main(String[] args) {
		System.out.println("---- Extract the title from this XHTML content ----");
		t1();
		System.out.println("---- Find multiple elements nested in the same string ----");
		t2();
		System.out.println("---- Find text that is delimited by the same character ----");
		t3();
	}
	
	private  static void t1() {
		String htmlContent = "<html>\n" +
        "  <head>\n" +
        "    <title>Test Page</title>\n" +
        "  </head>\n" +
        "  <body>\n" +
        "    <p>This is a TEST!</p>\n" +
        "  </body>\n" +
        "</html>";
		// Extract the title from this XHTML content
		String title = StringUtils.substringBetween(htmlContent, "<title>", 
			"</title>");
		System.out.println( "Title: " + title ); // Test Page
	}
	
	// Find multiple elements nested in the same string
	private static void t2() {
		String variables = "{45}, {35},  {120}  ,{168}" ;
		String[] arrVariables = variables.split("[ ]*,[ ]*");
		Double[] temp = new Double[arrVariables.length];
		for (int i = 0; i < arrVariables.length; i++) {
			String strValue = StringUtils.substringBetween(arrVariables[i], "{", "}");
			temp[i] = Double.parseDouble(strValue);
		}
		double sum = StatUtils.sum( ArrayUtils.toPrimitive( temp ) );
		System.out.println( "Variables: " + variables + " Sum: " + sum );
	}
	
	//  Find text that is delimited by the same character
	private static void t3() {
		String message = "|TESTING| BOUNDARYExampleBOUNDARY";
		String first = StringUtils.substringBetween( message, "|"); 
		String second = StringUtils.substringBetween( message, "BOUNDARY");
		System.out.println(first);
		System.out.println(second);
	}
}
